package com.nerve.android.cloudoffice.app.activity.im;

import java.util.ArrayList;
import java.util.List;

import org.nerve.android.annotation.Acvitity;
import org.nerve.android.annotation.ViewOnId;
import org.nerve.util.DateUtil;

import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.nerve.android.cloudoffice.OfficeApplication;
import com.nerve.android.cloudoffice.R;
import com.nerve.android.cloudoffice.app.NavigationActivity;
import com.nerve.android.cloudoffice.app.activity.assist.UserSelectActivity;
import com.nerve.android.cloudoffice.app.worker.MessageLoadListener;
import com.nerve.android.cloudoffice.app.worker.MessageLoadManager;
import com.nerve.android.cloudoffice.common.Const;
import com.nerve.android.cloudoffice.domain.Message;
import com.nerve.android.cloudoffice.service.data.MessageData;

/**
 * 
 * @project Cloudoffice MessageActivity.java
 * @datetime Aug 12, 2013 12:50:11 PM
 * @description 
 *    
 * @author 集成显卡 IBM 
 *			zxingming@qq.com
 *			zengxm@cn.ibm.com
 *
 * @change log:
 *
 */
@Acvitity(layout=R.layout.activity_message)
public class MessageActivity extends NavigationActivity implements MessageLoadListener{

	@ViewOnId(id=R.id.gridView1)
	private ListView listView;
	@ViewOnId(id=R.id.message_empty)
	private TextView messageTV;
	
	private int userId;//当前登录的id
	@SuppressWarnings("unused")
	private int targetId;//聊天对象id
	
	private List<Message> messageList = new ArrayList<Message>();
	private MessageAdapter adapter;
	
	private boolean onBackGround ;//是否被隐藏了
	
	@Override
	protected void initUI() {
		super.initUI();
		
		setNavTitle("我的消息");
		customNavigateRightButton("新增会话", true);
		showNavigateBackButton(false);
		
		listView.setEmptyView(messageTV);
		
		adapter = new MessageAdapter();
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Message m = messageList.get(arg2);
				
				viewSession(
						m.getFromId() == OfficeApplication.getLoginId()? m.getToId(): m.getFromId(),
						((TextView)arg1.findViewById(R.id.username)).getText().toString()
						);
			}
		});

		loadData();
		MessageLoadManager.addListener(this);
	}
	
	@Override
	public void onMessageLoaded(int size) {
		Const.log("MessageLoadListener -------------onMessageLoaded   size="+size);
		//当消息加载完成后
		if(size > 0 && !onBackGround){
			loadData();
		}
	}
	
	@Override
	public String getLoaderName() {
		return "message_session_list";
	}
	
	private void loadData(){
		Message tempL = null;
		if(messageList.size() > 0)
			tempL = messageList.get(0);
		
		messageList = MessageData.getSessionList(userId);
		Const.log("MessageActivity ::::::: 得到的messageList==" + messageList.size());
		
		for(Message m:messageList){
			if(tempL != null && m.getFromId()!=userId && m.getId() > tempL.getId())
				m.setRead(false);
			
			Const.log(m);
		}
		adapter.notifyDataSetChanged();
	}
	
	
	@Override
	protected void initData() {
		this.userId = OfficeApplication.getLoginId();
	}
	
	@Override
	protected void onNavigateRightButtonClick() {
		Intent intent = new Intent(this, UserSelectActivity.class);
		startActivityForResult(intent, 0);
	}
	
	/**
	 * 选择用户时的返回
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		this.onBackGround = false;
		
		if(requestCode == 0){
			if(data == null)
				return ;
			String info = data.getStringExtra(UserSelectActivity.INFO);
			int id = data.getIntExtra(UserSelectActivity.ID, -1);
			
			if(id > 0 && info.indexOf(Const.SPLIT) > -1){
				if(id == OfficeApplication.getLoginId()){
					toast("不能跟自己交谈");
					return ;
				}
				
				Const.log("选择了聊天对象：" + info);
				viewSession(id, info.split(Const.SPLIT)[1]);
			}
		}else if(requestCode == 1){
			loadData();
		}
	}
	
	private void viewSession(int targetId, String name){
		Intent intent = new Intent(this, MessageViewActivity.class);
		intent.putExtra(MessageViewActivity.NAME, name);
		intent.putExtra(MessageViewActivity.ID, targetId);
		
		this.onBackGround = true;
		startActivityForResult(intent, 1);
	}
	
	
	/**
	 * 在这里拦截返回键的事情，就可以达到统一退出程序
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	private class MessageAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			return messageList.size();
		}

		@Override
		public Object getItem(int arg0) {
			return messageList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int arg0, View view, ViewGroup arg2) {
			Message m = (Message)getItem(arg0);
			if(view == null)
				view = View.inflate(MessageActivity.this, R.layout.activity_message_listitem, null);
			
			String name = m.getFromId() == userId? m.getToUser(): m.getFromUser();
			((TextView)view.findViewById(R.id.username)).setText(name);
			((TextView)view.findViewById(R.id.content)).setText(m.getMessage());
			
			
			TextView counter = (TextView)view.findViewById(R.id.message_counter);
			counter.setText("1");
			Const.log("MessageAdapter :::::::::::; isRead = " + m.isRead());
			counter.setVisibility(m.isRead() ? View.GONE : View.VISIBLE);
			
			((TextView)view.findViewById(R.id.date)).setText(DateUtil.toString(m.getJoinDate(), "MM-dd HH:mm"));
			return view;
		}
	}
}